package com.ecube.maintenance.components.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.SellerAction;
import com.ecube.maintenance.biz.commons.Constants;
import com.ecube.maintenance.biz.commons.ICCallBack;
import com.ecube.maintenance.biz.commons.ICTException;
import com.ecube.maintenance.biz.commons.VolleySingleton;
import com.ecube.maintenance.components.activity.MainActivity;
import com.ecube.maintenance.components.application.CCBApplication;
import com.ecube.maintenance.components.widget.LoadingDialog;
import com.ecube.maintenance.components.widget.QuickSearchView;
import com.ecube.maintenance.pojos.AddressInfo;
import com.ecube.maintenance.pojos.SellerInfo;
import com.ecube.maintenance.pojos.SellerListInfo;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;
import com.ecube.maintenance.utils.TimeUtil;
import com.fourmob.datetimepicker.date.DatePickerDialog;

import java.security.InvalidParameterException;
import java.util.Calendar;
import java.util.List;

/**
 * #0
 * Created by wcx on 14-9-7.
 * 4S店商家展示页面
 */

public class DealerListFragment extends CustomFragment implements DatePickerDialog.OnDateSetListener {
    public static final String DATE_PICKER_TAG = "date_picker";
    public static final String DATE_STRING = "date_string";
    public static final String SORT_BY = "sort_by";
    public static final String QUERY = "query";

    boolean initLoad = true;
    TextView mEmptyText;
    private UserInfo mUserInfo = UserInfo.getInstance();
    private ListView mDealerListView;
    private TextView mDatePicker;
    private Spinner mSortSpinner;
    private String dateString;
    private String sortBy;
    private String query;
    private LoadingDialog loadingDialog;
    private String curDateString = "";
    private String curSortBy = "";
    private String curQuery = "";
    private DealerListAdapter mDealerListAdapter;
    private QuickSearchView mSearchView;

    private boolean isSearchFragment = false;

    public DealerListFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static DealerListFragment newInstance() {
        DealerListFragment fragment = new DealerListFragment();
        fragment.setIsSearchFragment(false);
        return fragment;
    }

    public static DealerListFragment newInstance(Bundle args) {
        DealerListFragment fragment = new DealerListFragment();
        fragment.setArguments(args);
        if (!args.containsKey(DATE_STRING) || !args.containsKey(SORT_BY) || !args.containsKey(QUERY))
            throw new InvalidParameterException("args must contains DATE_STRING,SORT_BY,and QUERY");
        fragment.setIsSearchFragment(true);
        return fragment;
    }

    public void setIsSearchFragment(boolean bool) {
        this.isSearchFragment = bool;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if (!isDrawerOpen()) {
            getActivity().getMenuInflater().inflate(R.menu.main, menu);
            if (isSearchFragment) {
                menu.findItem(R.id.action_search).setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {

                        return true;
                    }

                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        if (isSearchFragment) {
                            getFragmentManager().popBackStack();
                        }
                        return true;
                    }
                });
            }

            mSearchView = (QuickSearchView) menu.findItem(R.id.action_search).getActionView();
            if (isSearchFragment) {
                menu.findItem(R.id.action_search).expandActionView();
                mSearchView.setQuery(query, false);
                mSearchView.clearFocus();
            }


            mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String q) {
                    if (isSearchFragment) {
                        query = q;
                        loadNewList();
                        mSearchView.clearFocus();
                        return false;
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString(DATE_STRING, dateString);
                        bundle.putString(SORT_BY, sortBy);
                        bundle.putString(QUERY, q);
                        getFragmentManager().beginTransaction().hide(DealerListFragment.this)
                                .add(R.id.container, DealerListFragment.newInstance(bundle))
                                .addToBackStack(null).commit();
                        return false;
                    }

                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });
        }
    }

    public boolean isDrawerOpen() {
        return ((MainActivity) getActivity()).isDrawerOpen();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadingDialog = new LoadingDialog(getActivity());
        setFragmentTitle("");
    }

    private ActionBar getActionBar() {
        return getActivity().getActionBar();
    }

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        configureActionBar();
        super.onHiddenChanged(hidden);
    }

    private void configureActionBar() {
        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        actionBar.setDisplayShowTitleEnabled(false);
        View v = actionBar.getCustomView();
        if (v != null) {
            if (mSearchView == null || mSearchView.isIconified())
                v.setVisibility(View.VISIBLE);
            AddressInfo addressInfo = CCBApplication.sAddressInfo;
//            String cityName = PrefManager.getInstance().getString(Constants.PREF_CITY_NAME);
            String cityName = addressInfo.getAddress();
            ((TextView) v).setText(cityName == "" ? "成都" : cityName);
        }
        actionBar.setDisplayShowTitleEnabled(false);

    }

    private boolean isValidBundle(Bundle bundle) {
        if (bundle.containsKey(DATE_STRING) && bundle.containsKey(SORT_BY) && bundle.containsKey(QUERY))
            return true;
        else return false;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        initLoad = true;
        //特价
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        mDealerListView = (ListView) rootView.findViewById(R.id.authorized_dealer_list);
        //数据初始化
        Bundle args = getArguments();
        if (args != null && args.containsKey(DATE_STRING)) {
            dateString = args.getString(DATE_STRING);
            sortBy = args.getString(SORT_BY);
            query = args.getString(QUERY);
        } else {
            dateString = TimeUtil.tomorrowString();
            sortBy = Constants.SORT_DEFAULT;
            query = "";
        }

        mDatePicker = (TextView) rootView.findViewById(R.id.date_picker);
        mDatePicker.setText(dateString);
        mDatePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] t = mDatePicker.getText().toString().split("-");
                DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(DealerListFragment.this,
                        Integer.parseInt(t[0]), Integer.parseInt(t[1]) - 1,
                        Integer.parseInt(t[2]), true);
                datePickerDialog.setYearRange(2014, Calendar.getInstance().get(Calendar.YEAR));
                datePickerDialog.show(getFragmentManager(), DATE_PICKER_TAG);
            }
        });
        View footerView = ((LayoutInflater) getActivity()
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.item_list_load_more, null, false);
        footerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadMoreList();
            }
        });
        mDealerListView.addFooterView(footerView);

        //排序方式窗口
        mSortSpinner = (Spinner) rootView.findViewById(R.id.sort_spinner);
        mSortSpinner.setAdapter(new ArrayAdapter<String>(getActivity(),
                R.layout.item_list_sort_spinner, new String[]{"默认排序", "价格由低到高", "距离由近到远"}));

        mSortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (initLoad && isSearchFragment) {
                    if (sortBy.equals(Constants.SORT_NEAR2FAR))
                        mSortSpinner.setSelection(2);
                    else if (sortBy.equals(Constants.SORT_LOW2HIGH))
                        mSortSpinner.setSelection(1);
                    else mSortSpinner.setSelection(0);
                }
                switch (position) {
                    case 0:
                        sortBy = Constants.SORT_DEFAULT;
                        break;
                    case 1:
                        sortBy = Constants.SORT_LOW2HIGH;
                        break;
                    case 2:
                        sortBy = Constants.SORT_NEAR2FAR;
                        break;
                }
                if (initLoad) {
                    initLoad = false;
                    return;
                }
                loadNewList();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        mEmptyText = (TextView) rootView.findViewById(R.id.empty_text);
        mEmptyText.setVisibility(View.GONE);
        if (mDealerListAdapter == null) {
            AddressInfo addressInfo = CCBApplication.sAddressInfo;
            mDealerListAdapter = new DealerListAdapter(getActivity());
            fetchSPList(addressInfo, dateString, query, sortBy, 0);
        } else {
            mDealerListView.setAdapter(mDealerListAdapter);
        }
        return rootView;
    }

    private void loadMoreList() {
        int skip = mDealerListAdapter.getCount();
//        skip = 5;
        fetchSPList(CCBApplication.sAddressInfo, dateString, query, sortBy, skip);

    }

    private void loadNewList() {
        if (!curDateString.equals(dateString) || !curSortBy.equals(sortBy) || !curQuery.equals(query))
            fetchSPList(CCBApplication.sAddressInfo, dateString, query, sortBy, 0);
    }


    /**
     * @param addressInfo 定位信息
     * @param dateString  时间字符串
     * @param keyword     搜索关键字
     * @param sortBy      排序方式 see Constants
     * @param skip        跳过前面数据的条数
     */
    private void fetchSPList(AddressInfo addressInfo,
                             final String dateString,
                             final String keyword,
                             final String sortBy,
                             final int skip
    ) {
        Bog.v("skip[" + skip + "]-date[" + dateString + "]-sort[" + sortBy + "]-keyword[" + keyword + "]");
        if (addressInfo != null) {
            String carFactory = UserInfo.getInstance().getCarFactory();
            loadingDialog.setTipText(getString(R.string.message_loading_seller_list));
            loadingDialog.show();
            SellerAction.fetchSellerList(mUserInfo.getSid(), addressInfo,
                    skip, dateString, carFactory, keyword
                    , sortBy, new ICCallBack<SellerListInfo>() {
                        @Override
                        public void done(SellerListInfo result, ICTException exception) {
                            loadingDialog.getDialog().dismissDialogger();
                            if (exception != null) {
                                Bog.toast( exception.getMessage());
                                return;
                            }
                            curSortBy = sortBy;
                            curDateString = dateString;
                            curQuery = keyword;
                            if (skip == 0) {
                                mDealerListView.setAdapter(mDealerListAdapter);
                                mDealerListAdapter.setList(result);
                            } else {
                                if (result.getCount() != 0)
                                    mDealerListAdapter.appendList(result);
                                else Bog.toast("没有更多数据");
                            }
                            if (mDealerListAdapter.getCount() == 0) {
                                mEmptyText.setVisibility(View.VISIBLE);
                                mDealerListView.setVisibility(View.INVISIBLE);
                            } else {
                                mEmptyText.setVisibility(View.INVISIBLE);
                                mDealerListView.setVisibility(View.VISIBLE);
                            }
                        }
                    });
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        dateString = year + "-";
        month++;
        if (month < 10)
            dateString += "0";
        dateString += (month) + "-";

        if (day < 10)
            dateString += "0";
        dateString += (day) + "";

        mDatePicker.setText(dateString);
        loadNewList();
    }


    /**
     * 特价商家适配器
     */
    private class DealerListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private SellerListInfo mSellerListInfo;
        private Context mContext;

        public DealerListAdapter(Context context, SellerListInfo sellerListInfo) {
            this.inflater = LayoutInflater.from(context);
            this.mSellerListInfo = sellerListInfo;
            this.mContext = context;
        }

        public DealerListAdapter(Context context) {
            this.inflater = LayoutInflater.from(context);
            this.mContext = context;
        }

        public void setList(SellerListInfo sellerListInfo) {
            this.mSellerListInfo = sellerListInfo;
            notifyDataSetChanged();
        }

        public void appendList(SellerListInfo sellerListInfo) {

            List<SellerInfo> list = mSellerListInfo.getSpList();
            list.addAll(sellerListInfo.getSpList());
            mSellerListInfo.setSpList(list);
            int count = mSellerListInfo.getCount();
            mSellerListInfo.setCount(count);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mSellerListInfo == null ? 0 : mSellerListInfo.getCount();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            final SellerInfo sellerInfo = mSellerListInfo.getSpList().get(position);
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = this.inflater.inflate(R.layout.item_list_dealer, null);
                holder.logo = (ImageView) convertView.findViewById(R.id.dealer_img);
                holder.name = (TextView) convertView.findViewById(R.id.item_list_dealer_name);
                holder.brand = (TextView) convertView.findViewById(R.id.item_list_dealer_brand);
                holder.distance = (TextView) convertView.findViewById(R.id.item_list_dealer_distance);
                holder.discountPrice = (TextView) convertView.findViewById(R.id.item_list_dealer_discount_price);
                holder.originalPrice = (TextView) convertView.findViewById(R.id.item_list_dealer_original_price);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //店名
            holder.name.setText(sellerInfo.getSpName());
            //原价
            String origPrice = sellerInfo.getOrigPrice();
            if (origPrice != null)
                holder.originalPrice.setPaintFlags(holder.originalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            holder.originalPrice.setText(origPrice == null ? "无" : ("¥" + sellerInfo.getOrigPrice()));
            //现价
            holder.discountPrice.setText(sellerInfo.getDiscountPrice() == null ? "无" : ("¥" + sellerInfo.getDiscountPrice()));
            if(TextUtils.isEmpty(sellerInfo.getDiscountPrice())){
                holder.discountPrice.setVisibility(View.INVISIBLE);
            } else {
                holder.discountPrice.setVisibility(View.VISIBLE);
            }
            //品牌
            holder.brand.setText(sellerInfo.getCarBrand());
            //距离
            String[] distance = sellerInfo.getDistance().split("\\.");
            holder.distance.setText(distance[0] + "." + distance[1].substring(0, 1) + "km");
            ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(holder.logo,
                    R.drawable.dealer_example, R.drawable.dealer_example);
            String url = sellerInfo.getSpLogo();
            VolleySingleton.loadImage(url, imageListener);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager().beginTransaction()
                            .hide(DealerListFragment.this).add(R.id.container,
                            DealerDetailFragment.newInstance(dateString, sellerInfo))
                            .addToBackStack(null).commit();
                }
            });
            return convertView;
        }

        public class ViewHolder {
            TextView name;
            TextView brand;
            TextView discountPrice;
            TextView originalPrice;
            TextView distance;
            ImageView logo;

        }
    }


}
